/* vccd/scripts/install.c 
 * 
 * This file is part of vccd. 
 * 
 * vccd is free software: you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version. 
 * 
 * vccd is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 * GNU General Public License for more details. 
 * 
 * You should have received a copy of the GNU General Public License 
 * along with vccd. If not, see <https://www.gnu.org/licenses/>
 */ 




#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

#include <sys/stat.h>
#include <sys/types.h>

#include <vcc/vcc.h>
#include <vcc/vccd.h>


static const char usage[] = "Usage: install\n";

static inline int fatal(const char *s) {
	printf("fatal: %s\n", s);

	exit(1);
}

static inline int warn(const char *s) {
	fprintf(stderr, "warning: %s\n", s);

	return 0;
}


/* put $HOME to /etc/vccd-runtime */

int main(int argc, const char **argv) {
	char 	*home;
	char 	buf[PATH_MAX];
	int 	fd;

	if (unlikely(argc != 1)) 
		fatal(usage);
	
	if (unlikely(getuid())) 
		fatal("root required. ");

	if (unlikely(!(home = getenv("HOME")))) {
		warn("$HOME doesn't set. using './'. ");

		home = "./";
	}

	if (unlikely((fd = open("/etc/vccd-runtime", O_WRONLY | O_CREAT)) < 0)) {
		perror(argv[0]);

		return 1;
	}

	sprintf(buf, "%s/.vccd-runtime/", home);

	write(fd, buf, strlen(buf));
	close(fd);

	if (unlikely(mkdir(buf, 0777))) {
		perror(argv[0]);

		return 1;
	}

	sprintf(buf, "%s/.vccd-runtime/users", home);

	if (unlikely(mkdir(buf, 0777) < 0)) {
		perror(argv[0]);

		return 1;
	}

	return 0;
}


